package com.cyy.service;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service
public class HttpService {

    private Logger logger = LoggerFactory.getLogger(HttpService.class);


    private CloseableHttpClient getClient(){
        CloseableHttpClient client = HttpClients.createDefault();
        return HttpClients.createDefault();
    }


    public String post(String url,String body){
        logger.info("http post url={},body={}",url,body);
        HttpPost post = new HttpPost(url);
        StringEntity entity = new StringEntity(body,"utf-8");
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        post.setEntity(entity);



        try {
            HttpResponse response = this.getClient().execute(post);
            if(response.getStatusLine().getStatusCode() == 200) {
                HttpEntity he = response.getEntity();
                return EntityUtils.toString(he, "UTF-8");
            }
            throw new RuntimeException("rpc 请求错误 http status="+response.getStatusLine().getStatusCode());
        }catch (Exception e){
            throw new RuntimeException("rpc 请求错误");
        }
    }

}
